-- BeehiveM
-- Create by panyl
-- 蜂巢

module("BeehiveM", package.seeall);

-- 所有的蜂巢信息
local beehive = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    -- 转换下beehive信息表
    beehive = {};
    local beehive_CSV = get_beehive_CSV();
    for i = 1, #beehive_CSV do
        beehive[beehive_CSV[i].id] = beehive_CSV[i];
    end

    beehive_CSV = {};
end

-- 模块初始化
function init()
    loadCsv();

    EventMgr.removeAll("BeehiveM");
    EventMgr.register("BeehiveM", event.NEXT_FLOOR, function()
        -- 清空当前蜂巢数据
        -- ME.user.dbase:deleteTemp("beehive");
    end);
end

-- 检索
function query(id, path)
    local m = beehive[id];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 初始化蜂巢数据
function initBeehive(id, times, pos)
    local data = {
        ["id"] = id,
        ["times"] = times or 0,
    };

    -- local myData = ME.user.dbase:queryTemp("beehive", {});
    -- ME.user.dbase:setTemp("beehive", myData);

    -- myData[pos] = data;

    return { ["beehive"] = data, }
end

-- 获取蜂巢数据
function getBeehiveData(pos)
    local grid = DungeonM.getGridByPos(pos);
    local data = grid.beehive;
    return data or {};
end

-- 点击了蜂巢事件
function doEvent(pos)
    local grid = DungeonM.getGridByPos(pos);
    if not grid or grid.type ~= GRID_TYPE_BEEHIVE then
        trace("BeehiveM", "该格子不是蜂巢。")
        return false;
    end

    local data = grid.beehive;
    if not data then
        trace("BeehiveM", "没有蜂巢数据。");
        return false;
    end

    local id = data["id"];
    local times = data["times"];

    -- 次数已经用完了
    local maxTimes = query(id, "times");
    if (times >= maxTimes) then
        trace("BeehiveM", "次数用完了。");
        return false;
    end

    data["times"] = times + 1;

    -- 玩家受到伤害
    local damage = query(id, "damage") or 0;
    trace("BeehiveM", "蜂巢对玩家造成了%d点伤害。", damage);
    CombatM.receiveDamage(ME.user, ME.user, damage, 0, { delayPlay = true, });

    -- 获取当前翻开的最少血量的怪物
    local targets = {};
    local minHp = MAX_VALUE;    -- 随便一个大数

    local targetPos = 0;

    for pos = 1, GRID_SIZE do
        local grid = DungeonM.getGridByPos(pos);
        local monster = grid.monster;

        -- 如果是已翻开的未死亡的怪物
        if  grid:isOpened() and grid:isMonster() and
            monster and not monster:isDead() then
            if minHp > monster:getHp() then
                minHp = monster:getHp();
                targets = { monster, };
            elseif minHp == monster:getHp() then
                table.insert(targets, monster);
            end
        end
    end

    -- 没有目标
    if #targets <= 0 then
        trace("BeehiveM", "没有作用目标了。");

        targetPos = 0;
    else
        -- 随机一个目标
        local index = DungeonM.getRandSeed("behive_target") % #targets;
        local target = targets[index + 1];

        local layer = DungeonM.currentLayer();
        local power = query(id, "power") or 0;

        damage = math.modf(math.ceil(0.6 + power * layer));

        -- 传入攻击者信息
        local assailantInfo = {
            ["grid_type"] = GRID_TYPE_BEEHIVE,
        };

        -- 当作是玩家造成的伤害
        CombatM.receiveDamage(ME.user, target, damage, 0, { assailantInfo = assailantInfo, });

        targetPos = target:getPos();
        trace("BeehiveM", "对怪物(%d/%s)造成%d点伤害。", targetPos, target:getName(), damage);
    end

    -- 抛出蜂巢点击事件
    EventMgr.fire(event.BEEHIVE_DAMAGE, { ["pos"] = pos, ["targetPos"] = targetPos, });

    -- 如果次数已经用完了
    if data["times"] >= maxTimes then
        -- 将格子标记为已失效
        grid:changeState(GRID_STATE_DISABLE);

        -- 抛出蜂巢消失的事件
        EventMgr.fire(event.BEEHIVE_DISAPPEAR, { ["pos"] = pos, });

        local rand = DungeonM.getRandSeed("beehive_drop") % 100;
        local bonus;
        local drop1 = query(id, "drop1");
        local drop2 = query(id, "drop2");

        -- 如果是第一次掉落
        if CombatStatM.getFieldStat("beehive") <= 0 then
            bonus = { 1, query(id, "first_drop"), 1 };
        elseif rand < drop1["rate"] then
            -- 掉落率 20%
            bonus = { 1, drop1["class_id"], 1};
        elseif rand < drop1["rate"] + drop2["rate"] then
            bonus = { 1, drop2["class_id"], 1, };
        else
            -- nothing
        end

        if bonus then
            grid.bonus = bonus;
        end

        -- 增加统计
        CombatStatM.addFieldStat("beehive", 1);
    end

    DungeonM.addAction( {["cmd"] = "beehive", ["data"] = targetPos, ["pos"] = pos, } );

    if DungeonM.isCostRound(grid) then
        -- 抛出一个回合事件
        -- 这里需要指定延迟播放，等攻击动画播放完毕后再更新血量
        EventMgr.fire(event.COMBAT_ROUND, { ["pos"] = grid:getPos(), ["isDelay"] = true, } );
    end

    -- 通知建筑事件完成
    EventMgr.fire(event.BUILDING_EVENT_DONE, {["pos"] = pos,});

    return true, true;
end
